package com.haskie.user.controller;


import com.haskie.api.entity.User;
import com.haskie.api.utils.RedisUtil;
import com.haskie.user.configBean.UserConfig;
import com.haskie.user.service.IUserService;
import com.haskie.api.utils.RedissonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@Api(value = "用户controller", tags = {"用户操作接口"})
public class UserContrller {

    @Autowired
    IUserService userService;
    @Autowired
    UserConfig userConfig;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedissonUtil redissonUtil;

    @GetMapping("/getAllUser/{id}")
    @ApiOperation(value = "获取用户信息", tags = {"获取用户信息"}, notes = "通过ID获取")
    public User getAllUser(@ApiParam(name = "id", value = "用户id", required = true) @PathVariable("id") String id) {
        User user = userService.getAll(id);
        return user;
    }

    @GetMapping("/getConfig")
    @ApiOperation(value = "获取用户配置信息", tags = {"获取用户信息Apollo"}, notes = "apollo配置的用户信息")
    public Object getConfig() {

        return userConfig;
    }

    @GetMapping("/getRedisDate")
    @ApiOperation(value = "获取redis值", tags = {"集成redis验证"}, notes = "集成redis验证")
    public String getRedisDate() {
        redisUtil.set("cjj", userConfig.getSex());
        return (String) redisUtil.get("cjj");
    }

    @GetMapping(value = "/redisLock/{lockId}")
    @ApiOperation(value = "redisson分布式锁", tags = {"集成redisson验证"}, notes = "集成redisson验证")
    public void test(@PathVariable("lockId") String lockId) {

        RLock lock = redissonUtil.getRLock(lockId);
        try {
            boolean bs = lock.tryLock(5, 6, TimeUnit.SECONDS);
            if (bs) {
                // 业务代码
                log.info("进入业务代码: " + lockId);

                lock.unlock();
            } else {
                Thread.sleep(300);
            }
        } catch (Exception e) {
            log.error("", e);
            lock.unlock();
        }
    }

}
